package com.mxin.network.interceptor.encrypt;

import com.mxin.util.encrypt.AESUtil;

import org.json.JSONObject;

import java.net.URLDecoder;
import java.nio.charset.Charset;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;

/**
 * Created by ：2020/7/30
 * author : Administrator
 */
public class DefaultEncryptImpl implements IEncryptListener {

    @Override
    public boolean isNeedEncrypt(String url) {
        return false;
    }

    @Override
    public String encryptData(String data) {
        return AESUtil.encrypt(data);
    }

    @Override
    public String encryptGetRequest(String data){
        //拼接加密后的url，参数字段自己跟后台商量，这里我用param，后台拿到数据先对param进行解密，解密后的数据就是请求的数据
        return "?data=" + encryptData(data);
    }

    @Override
    public RequestBody encryptPostRequest(RequestBody requestBody){
        try{
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            String requestData = URLDecoder.decode(buffer.readString(Charset.forName("UTF-8")).trim(), "utf-8");
            if(requestBody instanceof FormBody){
                JSONObject json = new JSONObject();
                String[] params = requestData.split("&");
                for (String param : params) {
                    String[] ps = param.split("=");
                    json.put(ps[0],ps.length>1?ps[1]:"");
                }
                requestData = json.toString();
            }
            //这里调用加密的方法，自行修改
            String encryptData = encryptData(requestData);
            /*构建新的请求体*/
            return RequestBody.create(requestBody.contentType(), encryptData);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void handlerEncryptRequest(Request.Builder newRequest){
        //自定义加密请求
        newRequest.addHeader("X-Access-Encrypter", "1");
    }

}
